package com.example.demo;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class main {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        try {
            jsonObject.put("user_id","1269838578");
            JSONObject tmp = new JSONObject();
            tmp.put("type","text");
            JSONObject data = new JSONObject();
            data.put("text","你好");
            tmp.put("data",data);
            jsonArray.put(tmp);
            jsonObject.put("message",jsonArray);
            // 创建一个JSONObject对象
            // 创建URL对象
            URL url = new URL("http://127.0.0.1:3000/send_private_msg");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            // 将JSONObject转换为字符串并写入请求体
            String jsonInputString = jsonObject.toString();
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 这里可以添加读取响应内容的代码
            // 例如：
                   BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                   String inputLine;
                   StringBuffer response = new StringBuffer();
                   while ((inputLine = in.readLine()) != null) {
                       response.append(inputLine);
                   }
                   in.close();
                   System.out.println(response.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
